import { FC, useState, useRef, useCallback } from "react"

import { Button } from "@/components/Button"
import { Text } from "@/components/Text"
import { sendStreamingChatCompletion, sendChatCompletion } from "@/services/api/openaiHK"
/**
 * SSE测试组件 - 用于调试SSE连接问题
 */
export const SSETest: FC = () => {
  const [isLoading, setIsLoading] = useState(false)
  const [messages, setMessages] = useState<string[]>([])
  const sseClientRef = useRef<any>(null)

  const testNormalRequest = useCallback(async () => {
    if (isLoading) return

    setIsLoading(true)
    setMessages([])

    console.log("Starting normal HTTP request test...")
    setMessages((prev) => [...prev, "Starting normal request..."])

    try {
      const response = await sendChatCompletion({
        model: "gpt-3.5-turbo",
        messages: [
          {
            role: "user",
            content: "Hello, please respond with a short message.",
          },
        ],
        max_tokens: 100,
        temperature: 0.7,
        top_p: 1,
        presence_penalty: 0,
      })

      console.log("Normal request response:", response)
      setMessages((prev) => [...prev, "Request completed"])
      setMessages((prev) => [...prev, response.choices[0]?.message?.content || "No content"])
      setIsLoading(false)
    } catch (error) {
      console.error("Normal request failed:", error)
      setMessages((prev) => [...prev, `[ERROR]: ${(error as Error).message}`])
      setIsLoading(false)
      Alert.alert("Request Failed", (error as Error).message)
    }
  }, [isLoading])

  const testSSE = useCallback(() => {
    if (isLoading) return

    setIsLoading(true)
    setMessages([])

    console.log("Starting SSE test...")

    try {
      sseClientRef.current = sendStreamingChatCompletion(
        {
          model: "gpt-3.5-turbo",
          messages: [
            {
              role: "user",
              content: "Hello, please respond with a short message.",
            },
          ],
          max_tokens: 100,
          temperature: 0.7,
          top_p: 1,
          presence_penalty: 0,
        },
        {
          onOpen: () => {
            console.log("SSE connection opened")
            setMessages((prev) => [...prev, "Connection opened"])
          },
          onMessage: (content: string) => {
            console.log("Received content:", content)
            setMessages((prev) => [...prev, content])
          },
          onComplete: () => {
            console.log("SSE stream completed")
            setMessages((prev) => [...prev, "[COMPLETED]"])
            setIsLoading(false)
          },
          onError: (error: Error) => {
            console.error("SSE error:", error)
            setMessages((prev) => [...prev, `[ERROR]: ${error.message}`])
            setIsLoading(false)
            Alert.alert("SSE Error", error.message)
          },
        },
      )
    } catch (error) {
      console.error("Failed to start SSE:", error)
      setMessages((prev) => [...prev, `[FAILED]: ${(error as Error).message}`])
      setIsLoading(false)
      Alert.alert("SSE Failed", (error as Error).message)
    }
  }, [isLoading])

  const stopSSE = useCallback(() => {
    if (sseClientRef.current) {
      sseClientRef.current.disconnect()
      sseClientRef.current = null
    }
    setIsLoading(false)
    setMessages((prev) => [...prev, "[STOPPED]"])
  }, [])

  return (
    <View style={{ padding: 20 }}>
      <Text style={{ fontSize: 18, marginBottom: 20 }}>SSE Test Component</Text>

      <View style={{ flexDirection: "row", gap: 10, marginBottom: 20 }}>
        <Button
          title={isLoading ? "Loading..." : "Test Normal"}
          onPress={testNormalRequest}
          disabled={isLoading}
        />
        <Button
          title={isLoading ? "Loading..." : "Test SSE"}
          onPress={testSSE}
          disabled={isLoading}
        />
        <Button title="Stop" onPress={stopSSE} />
      </View>

      <View style={{ borderWidth: 1, borderColor: "#ccc", padding: 10, minHeight: 200 }}>
        <Text style={{ fontSize: 16, marginBottom: 10 }}>Messages:</Text>
        {messages.map((msg, index) => (
          <Text key={index} style={{ marginBottom: 5, fontSize: 14 }}>
            {index + 1}: {msg}
          </Text>
        ))}
      </View>
    </View>
  )
}
